/*

This file is part of Ext JS 4

Copyright (c) 2011 Sencha Inc

Contact:  http://www.sencha.com/contact

GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file.  Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.

If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.

*/
Ext.define('Writer.Form', {
    extend: 'Ext.form.Panel',
    alias: 'widget.writerform',

    requires: ['Ext.form.field.Text'],

    initComponent: function(){
        this.addEvents('create');
        Ext.apply(this, {
            activeRecord: null,
            iconCls: 'icon-user',
            frame: true,
            title: 'ABM PROYECTOS',
            defaultType: 'textfield',
            bodyPadding: 5,
            fieldDefaults: {
                anchor: '100%',
            },
            items: [{
                fieldLabel: 'Id',
                name: 'id',
                type: 'int',
                fieldCls : 'x-item-disabled',
            },{
                fieldLabel: 'Nombre',
                name: 'nombre',
            }, {
                fieldLabel: 'Descripcion',
                name: 'descripcion',
            }, {
                fieldLabel: 'Nº Fases',
                name: 'nroFases',
                type: 'int',
            }],
            dockedItems: [{
                xtype: 'toolbar',
                items: [{
                    iconCls: 'icon-iniciar',
                    text: 'Iniciar',
                    disabled: true,
                    itemId: 'iniciar',
                    scope: this,
                    handler: this.onIniciar
                }, {
                    iconCls: 'icon-terminar',
                    text: 'Terminar',
                    disabled: true,
                    itemId: 'terminar',
                    scope: this,
                    handler: this.onTerminar
                }]
            },{
				weight: 1,
                xtype: 'toolbar',
                dock: 'bottom',
                ui: 'footer',
                items: ['->', {
                    iconCls: 'icon-save',
                    itemId: 'save',
                    text: 'Guardar',
                    disabled: true,
                    scope: this, 
                    handler: this.onSave
                }, {
                    iconCls: 'icon-user-add',
                    itemId: 'create',
                    text: 'Crear',
                    scope: this,
                    handler: this.onCreate
                }, {
                    iconCls: 'icon-reset',
                    text: 'Reset',
                    scope: this,
                    handler: this.onReset
                }, {
                    iconCls: 'icon-user-delete',
                    itemId: 'delete',
                    disabled: true,
                    scope: this, 
                    text: 'Eliminar',
                    scope: this,
                    handler: this.onDelete
                }]
            }]
        });
        this.callParent();
    },

    setActiveRecord: function(record){
        this.activeRecord = record;
        if (record) {
            this.down('#save').enable();
            this.down('#delete').enable();
            this.down('#iniciar').enable();
            this.down('#terminar').enable();
            this.down('#create').disable(); 
                       
            this.getForm().loadRecord(record);
        } else {
            this.down('#save').disable();
            this.down('#delete').disable();
            this.down('#create').enable(); 
            this.getForm().reset();
        }
    },

    onSave: function(){
        var form = this.getForm();

                    form.submit({
                        
                        url: '/modificarProyecto',
                        params: {
								submit: 'submit'
						},
						method: "post",
                        success: function(form, action) {
                           Ext.Msg.alert('Proyecto modificado satisfactoriamente');
                           form.reset();
                        },
                        failure: function(form, action) {
                            Ext.Msg.alert('Error - No se ha podido modificar el proyecto');
                        }
                    });



    },

    onCreate: function(){
        var form = this.getForm();

                    form.submit({
                        
                        url: '/crearProyecto',
                        params: {
								submit: 'submit'
						},
						method: "post",
                        success: function(form, action) {
                           Ext.Msg.alert('Proyecto creado satisfactoriamente');
                           form.reset();
                        },
                        failure: function(form, action) {
                            Ext.Msg.alert('Error - No se ha podido crear el proyecto');
                        }
                    });



    },

    onDelete: function(){ 
        var form = this.getForm();

                    form.submit({
                        
                        url: '/eliminarProyecto',
                        params: {
								submit: 'submit'
						},
						method: "post",
                        success: function(form, action) {
                           Ext.Msg.alert('Proyecto eliminado satisfactoriamente');
                           form.reset();
                        },
                        failure: function(form, action) {
                            Ext.Msg.alert('Error - No se ha podido eliminar el proyecto');
                        }
                    });

	

    },


    onReset: function(){
        this.setActiveRecord(null);
        this.getForm().reset();
    },
    
    onIniciar: function(){
	
	        var form = this.getForm();

                    form.submit({
                        
                        url: '/iniciarProyecto',
                        params: {
								submit: 'submit'
						},
						method: "post",
                        success: function(form, action) {
                           Ext.Msg.alert('Proyecto iniciado satisfactoriamente');
                           form.reset();
                        },
                        failure: function(form, action) {
                            Ext.Msg.alert('Error - No se ha podido iniciar el proyecto');
                        }
                    });
    },
    
    onTerminar: function(){
		
    	        var form = this.getForm();

                    form.submit({
                        
                        url: '/terminarProyecto',
                        params: {
								submit: 'submit'
						},
						method: "post",
                        success: function(form, action) {
                           Ext.Msg.alert('Proyecto terminado satisfactoriamente');
                           form.reset();
                        },
                        failure: function(form, action) {
                            Ext.Msg.alert('Error - No se ha podido terminar el proyecto');
                        }
                    });},    
    
});


Ext.define('Writer.Grid', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.writergrid',

    requires: [
        'Ext.grid.plugin.CellEditing',
        'Ext.form.field.Text',
        'Ext.toolbar.TextItem'
    ],

    initComponent: function(){

        this.editing = Ext.create('Ext.grid.plugin.CellEditing');

        Ext.apply(this, {
            iconCls: 'icon-grid',
            frame: true,
            plugins: [this.editing],
            dockedItems: [{ //toolbar para filtrado	falta
                weight: 1,
                xtype: 'toolbar',
                dock: 'bottom',
                ui: 'footer',
                items: ['->', {
                    iconCls: 'icon-refresh',
                    text: 'Actualizar',
                    scope: this,
                    handler: this.onSync
                }]
            }],
            columns: [{
                text: 'Id',
                width: 30,
                sortable: true,
                dataIndex: 'id'
            },{
                header: 'Nombre',
                flex: 1,
                sortable: true,
                dataIndex: 'nombre',

            }, {
                header: 'Descripcion',
                flex: 1,
                sortable: true,
                dataIndex: 'descripcion',

            },{
                text: 'Nº Fases',
                flex: 1,
                sortable: true,
                dataIndex: 'nroFases'
            },{
                header: 'Fecha Creacion',
                flex: 1,
                dataIndex: 'fecha',

            }, {
                header: 'Estado',
                flex: 1,
                sortable: true,
                dataIndex: 'estado',

            }]
        });
        this.callParent();
        this.getSelectionModel().on('selectionchange', this.onSelectChange, this);
    },
    

    onSync: function(){
		this.store.load();
    },


    onAddClick: function(){
        var rec = new Writer.Person({
            first: '',
            last: '',
            email: ''
        }), edit = this.editing;

        edit.cancelEdit();
        this.store.insert(0, rec);
        edit.startEditByPosition({
            row: 0,
            column: 1
        });
    }
});

Ext.define('Writer.Person', {
    extend: 'Ext.data.Model',
    fields: [{
        name: 'id',
        type: 'int',
        useNull: true
    },{
        name: 'nroFases',
        type: 'int',
    }, 'nombre', 'descripcion', 'fecha', 'estado'],
    validations: [{
        type: 'length',
        field: 'email',
        min: 1
    }, {
        type: 'length',
        field: 'first',
        min: 1
    }, {
        type: 'length',
        field: 'last',
        min: 1
    }, {
        type: 'length',
        field: 'nombreUsuario',
        min: 1
    }]
});



Ext.require([
    'Ext.data.*',
    'Ext.tip.QuickTipManager',
    'Ext.window.MessageBox',
    
    'Ext.tab.*',
    'Ext.window.*',
    'Ext.tip.*',
    'Ext.layout.container.Border',
    
    'Ext.form.field.ComboBox',
    'Ext.form.FieldSet'
]);

Ext.onReady(function(){
    Ext.tip.QuickTipManager.init();
    var store = Ext.create('Ext.data.Store', {
        model: 'Writer.Person',
        autoLoad: true,
        autoSync: true,
        proxy: {
            type: 'ajax',
            url: '/listarProyectos',
            reader: {
                type: 'json',
                successProperty: 'success',
                root: 'data',
                messageProperty: 'message'
            },
            writer: {
                type: 'json',
                writeAllFields: false,
                root: 'data'
            },

        },
        listeners: {
            write: function(proxy, operation){
                if (operation.action == 'destroy') {
                    main.child('#form').setActiveRecord(null);
                }
                Ext.example.msg(operation.action, operation.resultSet.message);
            }
        },
        
        sorters: [{
            property: 'id',
            direction: 'ASC'
        }]        
    });
    



                win = Ext.create('widget.panel', {
				renderTo: 'comboProyecto',
                width: 900,
                height: 360,
                layout: 'border',
                bodyStyle: 'padding: 5px;',
				y: 20,
				x: 20,
                items: [{
                    region: 'west',
					xtype: 'writerform',
					itemId: 'form',
					width: 300,
/*
					listeners: {
						create: function(form, data){
							store.insert(0, data);
						}
					}*/
				}, {
                    region: 'center',
					xtype: 'writergrid',            
					itemId: 'grid',
					title: 'LISTADO PROYECTOS',

					flex: 1,        
					width: 680,
					height: 380,

					store: store,
					listeners: {
						selectionchange: function(selModel, selected) {
							win.child('#form').setActiveRecord(selected[0] || null);
						}
					}
				}]
            });
            win.show()
    

    
});

